package com.banmao.algorithm.No101To200.No102;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class Solution1 {

    public List<List<Integer>> levelOrder(TreeNode root) {

        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        if(root == null) {
            return new ArrayList<>();
        }

        queue.push(root);

        ArrayList<List<Integer>> result = new ArrayList<>();

        while(!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode pop = queue.poll();
                list.add(pop.val);
                if (pop.left != null) {
                    queue.add(pop.left);
                }
                if (pop.right != null) {
                    queue.add(pop.right);
                }
            }
            result.add(list);
        }

        return result;


    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
